<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of HttpTriggerAction
 *
 * @author Levz
 */
class HttpTriggerAction extends CAction {

    public function run() {
        $lastBroadcast = Yii::app()->user->instance->group->last_broadcast_time;

        $domain = Yii::app()->settings->get('frontlinesms', 'domain');
        $portNumber = Yii::app()->settings->get('frontlinesms', 'portNumber');
        $destinationPhoneNumber = Yii::app()->settings->get('frontlinesms', 'destinationPhoneNumber');
        $timeInterval = Yii::app()->settings->get('frontlinesms', 'timeInterval');

        if ($this->getTimeDifference(strtotime($lastBroadcast), time()) >= $timeInterval OR $lastBroadcast === null) {
            if ($prices = Price::model()->getPendingPrices($lastBroadcast)) {

                $url = 'http://' .
                        $domain .
                        ':' .
                        $portNumber .
                        '/send/sms/' .
                        $destinationPhoneNumber .
                        '/' .
                        urlencode(base64_encode(json_encode($prices))) .
                        '/';

                if ($this->runSmsSenderCommand($url)) {
                    if (Yii::app()->user->updateLastBroadcastTime()) {
                        echo CJSON::encode(array(
                            'message' => '<div class="modal-body">crop prices has been sent.</div>'
                        ));
                    }
                } else {
                    echo CJSON::encode(array(
                        'message' => '<div class="modal-body">message sending failed.</div>'
                    ));
                }
            } else {
                echo CJSON::encode(array(
                    'message' => '<div class="modal-body">no data to be sent.</div>'
                ));
            }
        } else {
            echo CJSON::encode(array(
                'message' => '<div class="modal-body">Please try again in a few moment.</div>'
            ));
        }
    }

    private function getTimeDifference($reference, $pointer) {
        return floor(abs($pointer - $reference) / 60);
    }

}

?>
